import Result from "../utils/Result";

import {Application} from "egg";

export default function (_, app: Application)  {
    return async function authMiddle(ctx, next) {
        const token = ctx.cookies.get("token",{
            signed: false
        });
        // 1.排除不需要验证 token 的路由
        if (app.config.routerWhiteList?.filter(el=>el == ctx.request.url)?.length ) return await next();
        console.log(ctx.request.url)
        if (token) {
            try {
                // 解码token
                let decode = ctx.app.jwt.verify(token, _.secret);
                ctx.logger.info(decode,"用户信息")
                if(decode?.id){
                    let auth = await ctx.app.redis.get(decode?.id);
                    if(!auth){
                        ctx.logger.error("token失效")
                        ctx.status = 401;
                        ctx.body = Result.setData({
                            code:401,
                            msg:"token失效！"
                        })
                        return;
                    }
                }
                await next(decode);
            } catch (error) {
                ctx.logger.error(error.message)
                ctx.status = 401;
                ctx.body = Result.setData({
                    code:401,
                    msg:error.message
                })
                return;
            }
        } else {
            ctx.logger.error("没有Token!")
            ctx.status = 401;
            ctx.body = Result.setData({
                code:401,
                msg:"没有Token!"
            })
            return;
        }
    };
};